package com.scuec.groupfive.service.impl;

import com.scuec.groupfive.entity.StudyPlan;
import com.scuec.groupfive.mapper.StudyPlanMapper;
import com.scuec.groupfive.service.StudyPlanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Collections;

@Service
public class StudyPlanServiceImpl implements StudyPlanService {

    private static final Logger logger = LoggerFactory.getLogger(StudyPlanServiceImpl.class);

    @Autowired
    private StudyPlanMapper studyPlanMapper;

    @Override
    public List<StudyPlan> findTodayPlans(Long userId) {
        try {
            logger.info("Finding today plans for userId: {}", userId);

            // 首先测试简单的查询
            int count = studyPlanMapper.countByUserId(userId);
            logger.info("Total plans count for userId {}: {}", userId, count);

            List<StudyPlan> plans = studyPlanMapper.findTodayPlans(userId);
            logger.info("Found {} plans for userId: {}", plans.size(), userId);
            return plans;
        } catch (Exception e) {
            logger.error("Error finding today plans for userId: {}", userId, e);
            throw new RuntimeException("获取今日计划失败: " + e.getMessage(), e);
        }
    }

    @Override
    public List<String> findCompletedDays(Long userId, String month) {
        try {
            logger.info("Finding completed days for userId: {} and month: {}", userId, month);
            List<String> days = studyPlanMapper.findCompletedDays(userId, month);
            logger.info("Found {} completed days for userId: {} and month: {}", days.size(), userId, month);
            return days;
        } catch (Exception e) {
            logger.error("Error finding completed days for userId: {} and month: {}", userId, month, e);
            return Collections.emptyList(); // 返回空列表而不是抛出异常
        }
    }

    @Override
    @Transactional
    public StudyPlan addPlan(StudyPlan plan) {
        if (plan.getContent() == null || plan.getContent().trim().isEmpty()) {
            throw new IllegalArgumentException("任务内容不能为空");
        }

        if (plan.getStatus() == null || plan.getStatus().trim().isEmpty()) {
            plan.setStatus("active"); // 默认设置为 active
        } else if (!plan.getStatus().equals("active") &&
                !plan.getStatus().equals("paused") &&
                !plan.getStatus().equals("completed") &&
                !plan.getStatus().equals("abandoned")) {
            throw new IllegalArgumentException("状态值只能是 'active', 'paused', 'completed' 或 'abandoned'");
        }

        // 查询当前最大 plan_id
        Integer maxPlanId = studyPlanMapper.selectMaxPlanId();
        // 设置新的 plan_id
        plan.setPlanId(maxPlanId != null ? (long) (maxPlanId + 1) : 1L);
        // 设置目标科目ID（这里假设高等数学的ID是1）
        plan.setTargetSubjectId(1);

        // 插入新计划
        studyPlanMapper.insert(plan);
        return plan;
    }

    @Override
    @Transactional
    public StudyPlan updatePlan(StudyPlan plan) {
        StudyPlan existingPlan = studyPlanMapper.findById(plan.getTaskId());
        if (existingPlan == null) {
            throw new IllegalArgumentException("任务不存在");
        }

        if (plan.getStatus() != null && !plan.getStatus().equals("未完成") && !plan.getStatus().equals("已完成")) {
            throw new IllegalArgumentException("状态值只能是'未完成'或'已完成'");
        }

        studyPlanMapper.update(plan);
        return plan;
    }

    @Override
    @Transactional
    public void deletePlan(Long taskId, Long userId) {
        StudyPlan plan = studyPlanMapper.findById(taskId);
        if (plan != null && plan.getUserId().equals(userId)) {
            studyPlanMapper.delete(taskId);
        }
    }

    @Override
    public List<StudyPlan> findHistoryUnfinishedPlans(Long userId) {
        try {
            logger.info("Finding history unfinished plans for userId: {}", userId);
            List<StudyPlan> plans = studyPlanMapper.findHistoryUnfinishedPlans(userId);
            logger.info("Found {} history unfinished plans for userId: {}", plans.size(), userId);
            return plans;
        } catch (Exception e) {
            logger.error("Error finding history unfinished plans for userId: {}", userId, e);
            return Collections.emptyList(); // 返回空列表而不是抛出异常
        }
    }
}